import { Module, Global } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { DatabaseBackupService } from './backup.service';
import { UtilsModule } from '../utils/utils.module';

/**
 * 数据库模块 - 基础设施层
 * 基于 NestJS 官方文档实现
 * 参考: https://docs.nestjs.cn/techniques/database
 * 对应 Java: MyBatis-Plus
 *
 * 职责：
 * - TypeORM 配置和连接管理
 * - 数据库备份和恢复服务
 * - 数据库相关的工具服务
 */
@Global()
@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('database.host', 'localhost'),
        port: configService.get('database.port', 3306),
        username: configService.get('database.username', 'root'),
        password: configService.get('database.password', 'root'),
        database: configService.get('database.database', 'wwjcloud'),
        entities: [
          __dirname + '/../**/*.entity{.ts,.js}',
          __dirname + '/../../config/**/*.entity{.ts,.js}',
        ],
        synchronize: true, // 临时启用自动同步来创建表
        logging: configService.get('database.logging', false),
        timezone: '+08:00',
        charset: 'utf8mb4',
        extra: {
          connectionLimit: 10,
          acquireTimeout: 60000,
          timeout: 60000,
        },
      }),
    }),
    UtilsModule,
  ],
  providers: [DatabaseBackupService],
  exports: [TypeOrmModule, DatabaseBackupService],
})
export class DatabaseModule {}
